package com.meng.ioc_demo;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.meng.hotfix.HotFix;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by Administrator on 2017/5/6.
 */

public class ProxyActivity extends AppCompatActivity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Button button = new Button(this);
        button.setText("启动插件");
        button.setTextColor(Color.BLUE);
        button.setTextSize(40);
        setContentView(button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                launchPlug();
            }
        });

    }

    /**
     * 判断加载插件
     */
    private void launchPlug() {
        File plugSdcardFile = new File(Environment.getExternalStorageDirectory().getPath()+"/0/plug.apk");
        if(plugSdcardFile.exists()){
            mDexPath = new File(getFilesDir(),"patch.dex").getAbsolutePath();
            //将插件从外部存储复制到内部存储
            copyPlugToInnerFile(plugSdcardFile,mDexPath);
            initDexClassLoader();
            String activityClass = getLaunchActivityFromApk(mDexPath);
            launchTargetActivity(activityClass);
        }else{
            Toast.makeText(this, "插件还没下载", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 将插件从外部存储复制到内部存储
     * @param plugSdcardFile
     * @param dexPath
     */
    private void copyPlugToInnerFile(File plugSdcardFile,String dexPath){
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(plugSdcardFile);
            File dstFile = new File(dexPath);
            fos = new FileOutputStream(dstFile);
            byte[] buff = new byte[1024];
            int len;
            while((len = fis.read(buff)) != -1){
                fos.write(buff,0,len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                }
            }
            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                }
            }
        }
    }

    private String mDexPath;

    /**
     * 从apk中获取第一个activity名字
     * @param apkPath
     * @return
     */
    private String getLaunchActivityFromApk(String apkPath){
        PackageInfo packageInfo = getPackageManager().getPackageArchiveInfo(mDexPath, PackageManager.GET_ACTIVITIES);
        if(packageInfo.activities != null
                && packageInfo.activities.length > 0){
            String activityName = packageInfo.activities[0].name;
            return activityName;
        }
        return null;
    }
//    private DexClassLoader dexClassLoader;
    private void initDexClassLoader(){
        File optimizedDirectory = getDir("dex", Context.MODE_PRIVATE);
//        dexClassLoader = new DexClassLoader(
//                mDexPath, optimizedDirectory.getAbsolutePath(), null, getClassLoader());
        HotFix.getInstance().inject(mDexPath);
    }
    private void launchTargetActivity(String clazz) {
        try {
            Class<?> loadClass = getClassLoader().loadClass(clazz);
            Log.e("ProxyActivity", "loadClass:" + loadClass);
            startActivity(new Intent(this,loadClass));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
